package com.android.fragmentdemo.thread7

import org.junit.Test
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors

class Demo7 {

    @Test
    fun testRunnable() {

        val executor = Executors.newFixedThreadPool(4)
        executor.execute(Task1())
        executor.execute(Task2())
        executor.execute(Task3())
        executor.execute(Task4())
        executor.shutdown()

        try {
            countDownLatch.await()
        } catch (ex: InterruptedException) {
            ex.printStackTrace()
        }

        println("map--content:${dataMap}")
    }

    class Task1 : Runnable {
        override fun run() {
            try {
                Thread.sleep(1000)
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            }
            dataMap["1"] = "1"
            println("我是任务--1")
            countDownLatch.countDown()
        }
    }

    class Task2 : Runnable {
        override fun run() {
            try {
                Thread.sleep(1000)
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            }
            dataMap["2"] = "2"
            println("我是任务--2")
            countDownLatch.countDown()
        }
    }

    class Task3 : Runnable {
        override fun run() {
            try {
                Thread.sleep(1000)
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            }
            dataMap["3"] = "3"
            println("我是任务--3")
            countDownLatch.countDown()
        }
    }

    class Task4 : Runnable {
        override fun run() {
            try {
                Thread.sleep(1000)
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            }
            dataMap["4"] = "4"
            println("我是任务--4")
            countDownLatch.countDown()
        }
    }

    companion object {
        private val dataMap = ConcurrentHashMap<String, String>()

        private val countDownLatch = CountDownLatch(4)
    }
}